#pragma once
#include "common.h"

namespace srpc
{
	#define ServicePool std::map<std::string, google::protobuf::Service *>
	#define ServicePoolIter std::map<std::string, google::protobuf::Service *>::iterator
	class TcpServer
	{
	public:
		TcpServer(int serverPort, int lengthOfQueueOfListen = 100, const std::string &boundIP = "")
		{
			mServerPort = serverPort;
			mLengthOfQueueOfListen = lengthOfQueueOfListen;
			mBoundIP = boundIP;
		}
		virtual ~TcpServer(){}
	public:
		int Start()
		{
			return 0;
		}
	private:
		void ServerFunction(int nConnectedSocket, int nListenSocket){}
		int mServerPort;
		int mLengthOfQueueOfListen;
		std::string mBoundIP;
	};

	// Rpc Channel Server必须实现以下的方法
	class RpcChannelServer
	{
	public:
		RpcChannelServer() {}
		virtual ~RpcChannelServer() {}
		virtual int Start() = 0;
		virtual void Close() = 0;
		virtual void RegisterService(google::protobuf::Service* service) = 0;
	protected:
		// 服务对象池
		ServicePool* mpServicePool; 
	};

	class TcpRpcChannelServer:public RpcChannelServer
	{
	public:
		TcpRpcChannelServer(uint16_t port, int32_t queueSize = 128):mPort(port),mQueueSize(queueSize) 
		{
			mpArgs = (pArgs)malloc(sizeof(pArgs));
			mpServicePool = new ServicePool();
		}
		virtual ~TcpRpcChannelServer() 
		{
			free(mpArgs);
			delete mpServicePool;
		}
		int Start();
		void Close();
		void RegisterService(google::protobuf::Service* service);
	private:
		void static do_accept(evutil_socket_t listener, short event, void *arg);
		void static read_cb(struct bufferevent *bev, void *arg);
		void static error_cb(struct bufferevent *bev, short event, void *arg);
		void static write_cb(struct bufferevent *bev, void *arg);
	private:
		typedef struct {
			ServicePool* pServicePool;
			EV_BASE pEventBase;
		}* pArgs;
		uint16_t mPort;
		int32_t mQueueSize;
		pArgs mpArgs;
	};

}
